//
//  YMTool.m
//  YMSwiftUI
//
//  Created by anscen on 2022/4/15.
//

#import "YMTool.h"
static NSString *ruleMore = @"第[0-9一二三四五六七八九十百千]*[章回].*";
static NSString *ruleLess = @"[0-9]{3,4}[\\s]+[\\S.]+";
@implementation YMTool
//
+ (NSString *)getDataFromTxt:(NSString *)name{
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"txt"];
   // NSString *path = [NSString stringWithFormat:@"%@/%@",[GDTXTDownInfo locationPath],name];
    NSURL *fileUrl = [NSURL fileURLWithPath:path];
    NSStringEncoding * usedEncoding = nil;
    NSError *error = nil;
    //带编码头的如 utf-8等 这里会识别
    NSString *body = [NSString stringWithContentsOfURL:fileUrl usedEncoding:usedEncoding error:&error];
    if(body&&!error){
        return body;
    }
    //如果之前不能解码，现在使用GBK解码
    NSLog(@"GBK");
    error = nil;
    body = [NSString stringWithContentsOfURL:fileUrl encoding:0x80000632 error:&error];
     if(body&&!error){
        return body;
    }
    //再使用GB18030解码
    NSLog(@"GBK18030");
    error = nil;
    body = [NSString stringWithContentsOfURL:fileUrl encoding:0x80000631 error:&error];
    if(body&&!error){
        return body;
    }
    return nil;
}
+ (NSArray *)getChapters:(NSString *)text rule:(NSString *)rule{
    NSArray *marr = [YMTool getChaptersContent:text rule:rule];
    NSMutableArray *strMarr = [[NSMutableArray alloc] init];
    NSRange lastRange = NSMakeRange(0, 0);
    for (int i = 0; i<marr.count; i++) {
        NSValue *value = marr[i];
        NSString *string = [text substringWithRange:NSMakeRange(lastRange.location, value.rangeValue.location - lastRange.location)];
        lastRange = value.rangeValue;
        if([string isEqualToString:@""]){
            string = @"\r\n";
        }
        [strMarr addObject:string];
    }
    //最后一章到结尾
    NSString *string = [text substringFromIndex:lastRange.location];
    if([string isEqualToString:@""]){
        string = @"\r\n";
    }
    if (string.length > 0) {
        [strMarr addObject:string];
    }
    return strMarr;
}
+ (NSArray *)getChaptersContent:(NSString *)text rule:(NSString *)rule{
    NSMutableArray *arrayRanges = [[NSMutableArray alloc] init];
    if (rule.length == 0){
        return nil;
    }
    NSRange rang = [text rangeOfString:rule options:NSRegularExpressionSearch];
    if (rang.location != NSNotFound && rang.length != 0){
        [arrayRanges addObject:[NSValue valueWithRange:rang]];
        NSRange rang1 = {0,0};
        NSInteger location = 0;
        NSInteger length = 0;
        for (int i = 0;; i++){
            if (0 == i){
                //去掉这个abc字符串
                location = rang.location + rang.length;
                length = text.length - rang.location - rang.length;
                rang1 = NSMakeRange(location, length);
            }else{
                location = rang1.location + rang1.length;
                length = text.length - rang1.location - rang1.length;
                rang1 = NSMakeRange(location, length);
            }
            //在一个range范围内查找另一个字符串的range
            rang1 = [text rangeOfString:rule options:NSRegularExpressionSearch range:rang1];
            if (rang1.location == NSNotFound && rang1.length == 0){
                break;
            }
            else{
                [arrayRanges addObject:[NSValue valueWithRange:rang1]];
            }
        }
        return arrayRanges.copy;
    }
    return nil;
}

+ (NSString *)getRegularString:(NSString *)string rule:(NSString *)rule{
    NSError *error = nil;
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:rule
                                                                                    options:0
                                                                                      error:&error];
    NSTextCheckingResult *result = [regularExpretion firstMatchInString:string options:NSMatchingReportProgress range:[string rangeOfString:string]];
    NSString *title = [string substringWithRange:result.range];
    return title;
}

+ (NSString *)stringURLEncode:(NSString *)url {
    if ([url respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
        /**
         AFNetworking/AFURLRequestSerialization.m
         
         Returns a percent-escaped string following RFC 3986 for a query string key or value.
         RFC 3986 states that the following characters are "reserved" characters.
            - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
            - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
         In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
         query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
         should be percent-escaped in the query string.
            - parameter string: The string to be percent-escaped.
            - returns: The percent-escaped string.
         */
        static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@?/"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
        static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
        
        NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
        [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
        static NSUInteger const batchSize = 50;
        
        NSUInteger index = 0;
        NSMutableString *escaped = @"".mutableCopy;
        
        while (index < url.length) {
            NSUInteger length = MIN(url.length - index, batchSize);
            NSRange range = NSMakeRange(index, length);
            // To avoid breaking up character sequences such as 👴🏻👮🏽
            range = [url rangeOfComposedCharacterSequencesForRange:range];
            NSString *substring = [url substringWithRange:range];
            NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
            [escaped appendString:encoded];
            
            index += range.length;
        }
        return escaped;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
        NSString *encoded = (__bridge_transfer NSString *)
        CFURLCreateStringByAddingPercentEscapes(
                                                kCFAllocatorDefault,
                                                (__bridge CFStringRef)url,
                                                NULL,
                                                CFSTR("!#$&'()*+,/:;=?@[]"),
                                                cfEncoding);
        return encoded;
#pragma clang diagnostic pop
    }
}
@end
